package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.Space;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ConfigTable;
import cn.bocweb.spinning.model.Bean.FinishExamBean;
import cn.bocweb.spinning.model.Bean.FirstMatchBean;
import cn.bocweb.spinning.model.Bean.FirstRewardBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.MatchShareBean;
import cn.bocweb.spinning.model.Bean.SecondTestBean;
import cn.bocweb.spinning.model.Bean.SecondTimeJudgeBean;
import cn.bocweb.spinning.model.Bean.TestDetailBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.util.WXUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.GlideCircle;
import cn.bocweb.spinning.view.common.MyDbHelper;
import cn.bocweb.spinning.view.dialog.TestResultDialog;
import de.greenrobot.event.EventBus;

public class TestResultActivity extends BaseActivity implements View.OnClickListener {

    TestResultDialog testResultDialog;
    String testid, libid, answer,isSchool;
    boolean isFirstMatch, isSecondTest;
    UserPresenter mUserPresenter;
    int friend_1_timeline_2;
    String isError = "1", isReset = "1", title, mtitle, end_time;
    //    MyDbHelper myDbHelper ;
//    DbUtils db;
//    ConfigTable config;
    boolean activityFinished, collectDeleted;
    @Bind(R.id.btn_exit)
    ImageView btnExit;
    @Bind(R.id.btn_check_answer)
    TextView btnCheckAnswer;
    @Bind(R.id.btn_check_wrong)
    TextView btnCheckWrong;
    @Bind(R.id.btn_rank)
    TextView btnRank;
    @Bind(R.id.exam_result_level)
    TextView examResultLevel;
    @Bind(R.id.exam_result_icon)
    ImageView examResultIcon;
    @Bind(R.id.exam_result_nickname)
    TextView examResultNickname;
    @Bind(R.id.exam_result_point)
    TextView examResultPoint;
    @Bind(R.id.exam_result_time_spend)
    TextView examResultTimeSpend;
    @Bind(R.id.exam_result_point_level)
    TextView examResultPointLevel;
    @Bind(R.id.exam_result_money)
    TextView examResultMoney;
    @Bind(R.id.exam_result_money_level)
    TextView examResultMoneyLevel;

    @Bind(R.id.test_result_share_friend)
    LinearLayout testResultShareFriend;
    @Bind(R.id.test_result_share_timeline)
    LinearLayout testResultShareTimeline;
    //    @Bind(R.id.test_result_rule)
//    TextView mTestResultRule;
//    @Bind(R.id.btn_reward)
//    TextView mBtnReward;
    @Bind(R.id.btn_repeat)
    TextView mBtnRepeat;
    @Bind(R.id.textview_score)
    TextView textviewScore;
    @Bind(R.id.space1)
    Space space1;
    @Bind(R.id.space0)
    Space space0;
    //    @Bind(R.id.space2)
//    Space space2;
    @Bind(R.id.space3)
    Space space3;
    @Bind(R.id.textview_title)
    TextView textviewTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_result);

        mUserPresenter = new UserPresenterImp();
        EventBus.getDefault().register(this);

        dialog.show();
//        myDbHelper = new MyDbHelper();
//        db = myDbHelper.getDbInstance(this);
        ButterKnife.bind(this);
        initDialog();
        initIntent();
        initClickBtn();
//        initQueryData();
    }

//    private void initQueryData() {
//        try {
//            config =  db.findFirst(Selector.from(ConfigTable.class).where("libtype", "=", libid));
//            isError = config.getIserror();
//            isReset = config.getIsresit();
//            end_time = config.getEnd();
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

//    public void onEventMainThread(FirstMatchBean bean) {
//        if (bean.getReturn_code() == 0) {
//            Intent intent = new Intent(this, ReadyTestActivity.class);
//            intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, bean.getId());
//            intent.putExtra(Constant.TO_TEST_RANK_IF_FIRST, true);
//            startActivity(intent);
//            finish();
//        }
//    }
//public void onEventMainThread(SecondTimeJudgeBean bean) {
//    long nowTime = System.currentTimeMillis();
//    long endTime = Long.parseLong(bean.getEnd()) * 1000;
//    activityFinished = nowTime > endTime;
//}

    public void onEventMainThread(TestDetailBean bean) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        if (bean.getReturn_code() == 0) {
            if (bean.getData().getScore().equals("100")) {
                btnCheckWrong.setVisibility(View.INVISIBLE);
            }
            libid = bean.getData().getLibtype();
            String icon = bean.getData().getUthumb();
            if (icon == null || icon.isEmpty()) {
                examResultIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
            } else {
                Glide.with(this).load(icon).transform(new GlideCircle(this)).into(examResultIcon);
            }
            String nickname = bean.getData().getNickname();
            if (nickname == null || nickname.isEmpty()) {
                examResultNickname.setText(Constant.NICKNAME_UNLOGIN);
            } else {
                examResultNickname.setText(nickname);
            }
            examResultLevel.setText(bean.getData().getTitle());
            examResultMoney.setText(bean.getData().getScope());
            examResultMoneyLevel.setText(bean.getData().getScopeintro());
            examResultPoint.setText(bean.getData().getScore());
            examResultPointLevel.setText(bean.getData().getSubtitle());
            isReset = bean.getData().getIsresit();
            isError = bean.getData().getIserror();

            int time = Integer.parseInt(bean.getData().getSpend_time());
            String timeSpend = (time / 60) + "分" + (time % 60) + "秒";
            examResultTimeSpend.setText(timeSpend);
            if (isReset.equals("1")) {
                mBtnRepeat.setVisibility(View.VISIBLE);
                space3.setVisibility(View.VISIBLE);
                btnCheckAnswer.setVisibility(View.GONE);
            } else {
                mBtnRepeat.setVisibility(View.GONE);
                btnCheckAnswer.setVisibility(View.VISIBLE);
                space0.setVisibility(View.VISIBLE);
            }
            if (isError.equals("1")) {
                btnCheckWrong.setVisibility(View.VISIBLE);
                space1.setVisibility(View.VISIBLE);
            } else {
                btnCheckWrong.setVisibility(View.GONE);
            }
//            long nowTime = System.currentTimeMillis();
//            long endTime = Long.parseLong(bean.getData().getEnd()) * 1000;
//            activityFinished = nowTime > endTime;
//            if (activityFinished) {
//                btnCheckAnswer.setVisibility(View.VISIBLE);
//            }
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }

    }
    public void onEventMainThread(FirstRewardBean bean) {
        if (bean.getReturn_code() == 0) {
            Intent intent = new Intent(this, FirstRewardActivity.class);
            intent.putExtra(Constant.TO_FIRST_REWARD, bean.getUrl());
            startActivity(intent);
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(MatchShareBean bean) {
        if (bean.getReturn_code() == 0) {
            if (friend_1_timeline_2 == 1) {
                if (title != null) {
                    WXUtil.WXShareToFriend(bean.getUrl(), this, "我参加了" + title + "，快来看看我考了第几名吧!", "我参加了" + title + "，快来看看我考了第几名吧!");
                } else {
                    WXUtil.WXShareToFriend(bean.getUrl(), this);
                }
            } else {
                if (title != null) {
                    WXUtil.WXShareToTimeline(bean.getUrl(), this, "我参加了" + title + "，快来看看我考了第几名吧!", "我参加了" + title + "，快来看看我考了第几名吧!");
                } else {
                    WXUtil.WXShareToTimeline(bean.getUrl(), this);
                }
            }
        }
    }


    private void initIntent() {
        Intent intent = getIntent();
        title = intent.getStringExtra(Constant.TO_REDAY_TEST_TITLE);
        testid = intent.getStringExtra(Constant.CHECK_ANSWER_LIBID);
        answer = intent.getStringExtra(Constant.TO_TEST_RESULT_ANSWER);
//        if (intent.getStringExtra(Constant.CHECK_ANSWER_SCHOOL)!=null) {
//            isSchool = intent.getStringExtra(Constant.CHECK_ANSWER_SCHOOL);
//        }else {
//            isSchool = "";
//        }
//        FinishExamBean.DataEntity dataEntity = (FinishExamBean.DataEntity) intent.getSerializableExtra(Constant.EXAM_RESULT);
//        space1.setVisibility(View.GONE);
//        isSecondTest = intent.getBooleanExtra(Constant.EXAM_RESULT_ISSECONDTEST, false);
//        libid = intent.getStringExtra(Constant.EXAM_RESULT_LIBID);
//        if (intent.getStringExtra(Constant.EXAM_RESULT_SPEND_TIME)==null) {
//            spend_time = intent.getStringExtra(Constant.EXAM_RESULT_SPEND_TIME);
//        }
//        isFirstMatch = intent.getBooleanExtra(Constant.EXAM_RESULT_ISFIRSTMATCH, false);
//        testid = dataEntity.getTestid();
//        examResultLevel.setText(dataEntity.getTitle());
//        String icon = dataEntity.getUthumb();
//        String nickname = dataEntity.getNickname();
//        if (icon == null || icon.isEmpty()) {
//            examResultIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
//        } else {
//            Glide.with(this).load(icon).transform(new GlideCircle(this)).into(examResultIcon);
//        }
//        if (nickname == null || nickname.isEmpty()) {
//            examResultNickname.setText(Constant.NICKNAME_UNLOGIN);
//        } else {
//            examResultNickname.setText(nickname);
//        }
//
//        examResultPoint.setText(String.valueOf(dataEntity.getScore()));
//        examResultPointLevel.setText(dataEntity.getSubtitle());
//        String min = String.valueOf(Integer.parseInt(spend_time) / 60);
//        String sec = String.valueOf(Integer.parseInt(spend_time) % 60);
//        examResultTimeSpend.setText(min + "分" + sec + "秒");
//
//        examResultMoney.setText(dataEntity.getScope());
//        examResultMoneyLevel.setText(dataEntity.getScopeintro());
//        if (isFirstMatch) {
//            textviewTitle.setVisibility(View.VISIBLE);
//            btnCheckAnswer.setVisibility(View.GONE);
//            btnCheckWrong.setVisibility(View.GONE);
//            btnRank.setText("排行榜");
//            textviewScore.setText("分数:");
////            mTestResultRule.setVisibility(View.VISIBLE);
//            if (dataEntity.getScore() > 80) {
////                mBtnReward.setVisibility(View.VISIBLE);
//                mBtnRepeat.setVisibility(View.GONE);
//                space1.setVisibility(View.VISIBLE);
//            } else {
//                space3.setVisibility(View.VISIBLE);
//                space1.setVisibility(View.VISIBLE);
//                mBtnReward.setVisibility(View.GONE);
//                mBtnRepeat.setVisibility(View.VISIBLE);
//            }
//        } else if (isSecondTest) {
////            textviewScore.setText("复赛分数:");
////            btnRank.setText("复赛排行榜");
//
//            textviewScore.setText("分数:");
//            btnRank.setText("排行榜");
//
//            textviewTitle.setVisibility(View.VISIBLE);
//            space2.setVisibility(View.VISIBLE);
//            btnCheckAnswer.setVisibility(View.GONE);
//            btnCheckWrong.setVisibility(View.GONE);
//            mTestResultRule.setVisibility(View.GONE);
//            mBtnRepeat.setVisibility(View.GONE);
//
//        } else {
//            LibListBean.DataEntity dataEntity1 = new LibListBean.DataEntity();
//            dataEntity1.readLibListIntoLocal(this);
//            textviewScore.setText(dataEntity1.getTitle() + "分数:");
//            mTestResultRule.setVisibility(View.GONE);
//            space0.setVisibility(View.VISIBLE);
//            space1.setVisibility(View.VISIBLE);
//        }


        LibListBean.DataEntity dataEntity1 = new LibListBean.DataEntity();
        dataEntity1.readLibListIntoLocal(this);
        if (title == null || TextUtils.isEmpty(title)) {
//            textviewScore.setText(dataEntity1.getTitle() + "分数:");
//            title = dataEntity1.getTitle();
            collectDeleted = false;
        } else {
//            textviewScore.setText(title + "分数:");
            collectDeleted = true;
        }
        if (answer == null || TextUtils.isEmpty(answer)) {
            mBtnRepeat.setVisibility(View.GONE);
            btnCheckAnswer.setVisibility(View.VISIBLE);
            space0.setVisibility(View.VISIBLE);
        } else {
            mBtnRepeat.setVisibility(View.VISIBLE);
            btnCheckAnswer.setVisibility(View.GONE);
            space3.setVisibility(View.VISIBLE);
        }
//        textviewScore.setText( "分数:");
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        if (title != null) {
            textviewTitle.setText("\t  " + title);
        } else {
            textviewTitle.setText("\t  " + dataEntity1.getTitle());
        }

        mUserPresenter.testDetail(dataEntity.getUserid(), testid);

//        if (dialog.isShowing()) {
//            dialog.dismiss();
//        }
    }

    private void initDialog() {
        testResultDialog = new TestResultDialog(this);
    }

    private void initClickBtn() {
        btnRank.setOnClickListener(this);
        btnCheckAnswer.setOnClickListener(this);
        btnCheckWrong.setOnClickListener(this);
        btnExit.setOnClickListener(this);
        testResultShareFriend.setOnClickListener(this);
        testResultShareTimeline.setOnClickListener(this);
        mBtnRepeat.setOnClickListener(this);
//        mBtnReward.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_rank: {
                LibListBean.DataEntity dataEntity1 = new LibListBean.DataEntity();
                dataEntity1.readLibListIntoLocal(this);
                intent = new Intent(TestResultActivity.this, RankActivity.class);
                intent.putExtra(Constant.TO_RANK_LIBID, libid);

                if (title != null) {
                    intent.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
                    intent.putExtra(Constant.TO_TEST_RANK_IF_FIRST, isFirstMatch);
                    intent.putExtra(Constant.TO_TEST_RANK_IF_SECOND, true);
                } else {
                    intent.putExtra(Constant.TO_REDAY_TEST_TITLE, dataEntity1.getTitle());
                    intent.putExtra(Constant.TO_RANK_TITLE, dataEntity1.getTitle());
                    intent.putExtra(Constant.TO_TEST_RANK_IF_FIRST, isFirstMatch);
                    intent.putExtra(Constant.TO_TEST_RANK_IF_SECOND, isSecondTest);
                }
                startActivity(intent);
                break;
            }
            case R.id.btn_check_answer: {
                intent = new Intent(TestResultActivity.this, CheckAnswerActivity.class);
                intent.putExtra(Constant.CHECK_ANSWER_TESTID, testid);
                intent.putExtra(Constant.CHECK_ANSWER_LIBID, libid);
                intent.putExtra(Constant.CHECK_COLLECT_DELETE, collectDeleted);
                startActivity(intent);
                break;
            }
            case R.id.btn_check_wrong: {
                if (isError.equals("1")) {
                    intent = new Intent(TestResultActivity.this, CheckAnswerActivity.class);
                    intent.putExtra(Constant.CHECK_ERROR_TESTID, testid);
                    startActivity(intent);
                    break;
                } else {
                    DeviceUtil.MyToast(this, "考试还未结束，暂不开放");
                }
            }
            case R.id.btn_exit: {
                finish();
                break;
            }
            case R.id.test_result_share_friend: {
                friend_1_timeline_2 = 1;
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                mUserPresenter.matchShare(dataEntity.getUserid(), testid);
                break;
            }
            case R.id.test_result_share_timeline: {
                friend_1_timeline_2 = 2;
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                mUserPresenter.matchShare(dataEntity.getUserid(), testid);
                break;
            }
//            case R.id.btn_reward: {
//                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
//                dataEntity.readInfoFromLocal(this);
//                mUserPresenter.getFirstReward(dataEntity.getUserid());
//                break;
//            }
            case R.id.btn_repeat: {
                if (isFirstMatch) {
//                    mUserPresenter.getFirstMatch();
//                    Intent intentFirst = new Intent(this, ReadyTestActivity.class);
//                    intentFirst.putExtra(Constant.TO_READY_TEST_NORMAL, libid);
//                    intentFirst.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
//                    startActivity(intentFirst);
                    finish();
                } else if (isReset.equals("1")) {
                    Intent intentSecond = new Intent(TestResultActivity.this, ReadyTestActivity.class);
                    intentSecond.putExtra(Constant.TO_READY_FIRST_TEST_ID, libid);
                    intentSecond.putExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, true);
                    intentSecond.putExtra(Constant.TO_SECOND_RULE_END_TIME, end_time);
                    intentSecond.putExtra(Constant.TO_REDAY_TEST_TITLE, title);
                    startActivity(intentSecond);
                    finish();
                } else if (isSecondTest) {
                    DeviceUtil.MyToast(this, "考试已结束");
                }
                break;
            }
        }
    }

    public void onEventMainThread(SecondTestBean bean) {
//        DeviceUtil.Log("bean = " + bean.getMsg());
//        if (bean.getReturn_code() == 0) {
//            Intent intent = new Intent(this, ReadyTestActivity.class);
//            intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, String.valueOf(bean.getId()));
//            intent.putExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, true);
//            startActivity(intent);
//            finish();
//        }
    }
}
